var OutOrderBalance = function () {
  var template = /* html */ `
    <div class="out-order-balance" v-loading.fullscreen.lock="loading">
      <search-btn-view btn-text="应付账款查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button size="medium" type="primary" @click="lookStat">查看汇总</el-button>
          <el-button size="medium" type="primary" @click="exportExcel">导出Excel</el-button>
          <el-button v-if="selectWarehouseList.length>0" size="medium" type="primary" @click="paymentMoneys">批量付款</el-button>
        </template>
        <template slot="right">
          <table-col-show-select v-if="tableHideColumnKey!==null" :table-name="tableName" :current-column-name="currentColumnName"
            :hide-column.sync="tableHideColumnKey">
          </table-col-show-select>
        </template>
        <div slot="search-content">
          <out-order-search-form :search="search"></out-order-search-form>
        </div>
      </search-btn-view>
      <div class="out-order-balance-stat" v-if="statData!==null&&warehouseList.length>0">
          <span style="margin-right:5px">
          <label>应付总额：</label>
          <span style="color:green">{{statData.totalMoney}}</span>
          <label>未付总额：</label>
          <span style="color:green;">{{statData.nonReceiptPaymentPrice}}</span>
          <label>已付总额：</label>
          <span style="color:green">{{statData.receiptPaymentPrice}}</span>
        </span>
        <span>提示：若未付款结算，结算金额为采购金额;若有付款，结算金额为实际付款金额</span>
      </div>
      <div class="order-balance-content">
        <el-table fit stripe border ref="inOutOrderBalance" :data="warehouseList" style="width: 100%" height="parent" @row-click="lookPaymentRcord"
          :hide-column-keys="getTableHideColumns()" @selection-change="selectionChange">
          <el-table-column :resizable="false" type="selection"  column-key="selection" key="selection "width="40px" fixed="left" align="center"
            :selectable="checkSelectable"></el-table-column>
          <el-table-column label="操作" column-key="handle" key="handle" :width="handleWidth" fixed="left" align="center">
            <template slot-scope="scope" v-if="scope.row.isBalance===0">
              <el-button type="primary" size="mini" @click="balanceOrder(scope.row)">结算</el-button>
              <el-button type="primary" size="mini" @click="paymentMoney(scope.row)">付款</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="orderId" key="orderId" label="订单编号" min-width="140px" header-align="center"></el-table-column>
          <el-table-column prop="factoryId" key="factoryId" label="工厂型号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="coustomId" key="coustomId" label="客户型号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="coustomOrderId" key="coustomOrderId" label="客户订单号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="supplierName" key="supplierName" label="供应商" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="technology" key="technology" label="加工工艺" min-width="100px" header-align="center"></el-table-column>
          <el-table-column prop="flowCycle" key="flowCycle" label="流程周期" min-width="80px" align="center"></el-table-column>
          <el-table-column prop="maching" key="maching" label="加工对象" min-width="130px" header-align="center"></el-table-column>
          <el-table-column column-key="colorList" key="colorList" label="颜色" min-width="120px" header-align="center">
            <template slot-scope="scope">
              <span>{{scope.row.colorList.join('+')}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="model" key="model" label="规格" min-width="100px" header-align="center"></el-table-column>
          <el-table-column prop="count" key="count" label="外协数量" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="unitPrice" key="unitPrice" label="单价" min-width="100px" align="center"></el-table-column>
          <el-table-column column-key="valuationCount" key="valuationCount" label="计价数量" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.valuationCount}}{{scope.row.valuationUint}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" key="totalPrice" label="外协金额" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="returnCount" key="returnCount" label="完成数量" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="returnValuationCount" key="returnValuationCount" label="完成计价数量" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="returnTotalPrice" key="returnTotalPrice" label="外协完成金额" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" column-key="returenTime" key="returenTime" label="完成时间" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isFinish!==2&&scope.row.returenTime!==''">{{moment(scope.row.returenTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="receiptPaymentPrice" key="receiptPaymentPrice" label="已付金额" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="addReducePrice" key="addReducePrice" label="增减金额" min-width="100px" align="center">
          </el-table-column>
          <el-table-column :resizable="false" column-key="isBalance" key="isBalance" label="是否结算" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('financeMgr.balance.'+scope.row.isBalance)}}</span>
            </template>
          </el-table-column>
          <el-table-column column-key="money" key="money" label="结算金额" min-width="80px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isBalance===1">{{scope.row.money}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="balanceTime" key="balanceTime" label="结算时间" width="100px" align="center"></el-table-column>
          <el-table-column prop="createUser" key="createUser" label="制单人" min-width="100px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" column-key="createTime" key="createTime" label="制单时间" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.createTime!==''">{{moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="remark" key="remark" label="备注" width="151px" header-align="center"></el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>

      <el-dialog :fullscreen="dialogType!=='detail'" :title="dialogTitle" :visible.sync="openDialog" :top="dialogType==='detail'?'10vh':'0'"
        custom-class="material-dialog" @closed="dialogClosed">
        <div style="overflow:auto" :style="dialogType==='detail'?'height:calc(80vh - 54px)':'100%'">
          <template v-if="openDialog">
            <balance-detail v-if="dialogType==='detail'" :warehouse="selectWarehouse"></balance-detail>
            <payment-form v-else-if="dialogType==='payment'" type="order" :warehouse="selectWarehouse" @pay-success="paySuccess">
              <template slot="table-column">
              <el-table-column prop="warehouse.orderId" key="orderId" label="订单编号" min-width="140px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.factoryId" key="factoryId" label="工厂型号" min-width="120px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.coustomId" key="coustomId" label="客户型号" min-width="120px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.coustomOrderId" key="coustomOrderId" label="客户订单号" min-width="120px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.supplierName" key="supplierName" label="供应商" min-width="120px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.technology" key="technology" label="加工工艺" min-width="100px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.flowCycle" key="flowCycle" label="流程周期" min-width="80px" align="center"></el-table-column>
              <el-table-column prop="warehouse.maching" key="maching" label="加工对象" min-width="130px" header-align="center"></el-table-column>
              <el-table-column column-key="colorList" key="colorList" label="颜色" min-width="120px" header-align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.warehouse.colorList.join('+')}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="warehouse.model" key="model" label="规格" min-width="100px" header-align="center"></el-table-column>
              <el-table-column prop="warehouse.count" key="count" label="外协数量" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.unitPrice" key="unitPrice" label="单价" min-width="100px" align="center"></el-table-column>
              <el-table-column column-key="valuationCount" key="valuationCount" label="计价数量" min-width="100px" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.warehouse.valuationCount}}{{scope.row.warehouse.valuationUint}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="warehouse.totalPrice" key="totalPrice" label="外协金额" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.returnCount" key="returnCount" label="完成数量" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.returnValuationCount" key="returnValuationCount" label="完成计价数量" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.returnTotalPrice" key="returnTotalPrice" label="外协完成金额" min-width="100px" align="center"></el-table-column>
              <el-table-column :resizable="false" column-key="returenTime" key="returenTime" label="完成时间" width="100px" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.warehouse.isFinish!==2&&scope.row.warehouse.returenTime!==''">
                    {{moment(scope.row.warehouse.returenTime).format('YYYY-MM-DD')}}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="warehouse.createUser" key="createUser" label="制单人" min-width="100px" header-align="center"></el-table-column>
              <el-table-column :resizable="false" column-key="createTime" key="createTime" label="制单时间" width="100px" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.warehouse.createTime!==''">{{moment(scope.row.warehouse.createTime).format('YYYY-MM-DD')}}</span>
                </template>
              </el-table-column>
              </template>
            </payment-form>
          </template>
        </div>
      </el-dialog>

      <el-dialog fullscreen class="dialog-fullscreen" title="外协应付汇总" :visible.sync="openStat">
        <div style="height:100%;overflow:auto">
          <out-order-balance-stat v-if="openStat" :search="search" @stat-closed="statClosed">
          </out-order-balance-stat>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [
      tablePaginationMixin(),
      tableColShowMixin('inOutOrderBalance')
    ],
    data: function () {
      var search = {
        startTime: moment().subtract(10, 'day').valueOf(),
        endTime: moment().valueOf(),
        orderId: '',
        companyOrderId: '',
        factoryId: '',
        customerId: '',
        customerOrderId: '',
        supplierId: '',
        technology: '',
        machining: '',
        prodCycleList: [],
        isBalance: '',
        startPrice: undefined,
        endPrice: undefined
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        warehouseList: [],
        statData: null,
        handleWidth: '80px',
        openDialog: false,
        openStat: false,
        dialogTitle: '',
        dialogType: null,
        selectWarehouse: null,
        selectWarehouseList: [],
        moment: moment,
        i18n: i18n
      };
    },

    created: function () {
      this.setWarehouseList(true);
    },

    methods: {
      setWarehouseList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;

        var postData = {
          start: start,
          length: pageSize
        };

        this.setPostData(postData);

        if (isSearch) {
          postData.isSum = true;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/getPutOutSumMoneyDetail', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);

            var totalMoney = res.sum,
              receiptPaymentPrice = res.receiptPaymentPrice;
            var nonReceiptPaymentPrice = _.round(totalMoney - receiptPaymentPrice, 2);
            if (nonReceiptPaymentPrice < 0) {
              nonReceiptPaymentPrice = 0;
            }

            self.statData = {
              totalMoney: totalMoney,
              receiptPaymentPrice: receiptPaymentPrice,
              nonReceiptPaymentPrice: nonReceiptPaymentPrice
            };
          }

          res = res.list;

          var warehouseList = res.returnData;
          var hasBalance = false;
          for (var i = 0; i < warehouseList.length; i++) {
            var warehouse = warehouseList[i];

            var valuationCount = warehouse.valuationCount;
            var unitPrice = warehouse.unitPrice;
            warehouse.totalPrice = _.round(valuationCount * unitPrice, 2);

            var returnValuationCount = warehouse.returnValuationCount;
            warehouse.returnTotalPrice = _.round(returnValuationCount * unitPrice, 2);

            warehouse.returenTime = SysUtil.formatString2Date(warehouse.returenTime);
            warehouse.approvalTime = SysUtil.formatString2Date(warehouse.approvalTime);
            warehouse.createTime = moment(warehouse.createTime).valueOf();

            var color = warehouse.color;
            var colorList = [];
            if (!SysUtil.isEmpty(color) && color !== '[]') {
              color = color.substring(1, color.length - 1);
              colorList = color.split(',');
              colorList = _.map(colorList, function (color) {
                return color.trim();
              });
            }
            warehouse.colorList = colorList;

            if (!hasBalance && warehouse.isBalance === 0) {
              hasBalance = true;
            }
          }

          var handleWidth = hasBalance ? '135px' : '80px';
          self.handleWidth = handleWidth;

          self.warehouseList = warehouseList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.location = false;
        });
      },

      setPostData: function (postData) {
        var search = this.search;
        var startTime = search.startTime;
        if (startTime !== null) {
          postData.startTime = moment(startTime).format('YYYY-MM-DD');
        }
        var endTime = search.endTime;
        if (endTime !== null) {
          postData.endTime = moment(endTime).format('YYYY-MM-DD');
        }
        var fields = ['orderId', 'companyOrderId', 'factoryId', 'customerId', 'customerOrderId', 'machining',
          'supplierId', 'technology', 'isBalance', 'startPrice', 'endPrice'
        ];
        SysUtil.setPostData(postData, search, fields);
        return postData;
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setWarehouseList(true);
      },

      pageChange: function () {
        this.setWarehouseList();
      },

      checkSelectable: function (warehouse) {
        return warehouse.isBalance === 0;
      },

      selectionChange: function (warehouseList) {
        this.selectWarehouseList = warehouseList;
      },

      lookPaymentRcord: function (warehouse, column) {
        var columnKey = column.columnKey;
        if (columnKey === 'handle') {
          return;
        }

        this.dialogTitle = '收付款记录';
        this.selectWarehouse = {
          id: warehouse.typeId,
          totalPrice: warehouse.totalPrice
        };
        this.dialogType = 'detail';
        this.openDialog = true;
      },

      paymentMoney: function (warehouse) {
        this.dialogTitle = '付款';
        this.selectWarehouse = warehouse;
        this.dialogType = 'payment';
        this.openDialog = true;
      },

      paymentMoneys:function(){
        var warehouseList = this.selectWarehouseList;
        if (warehouseList.length === 0) {
          this.$alert('请选择需要付款的外协单','信息');
          return;
        }
        var data = _.uniqBy(warehouseList, 'supplierName');
        if (data.length !== 1) {
          this.$alert('需要付款的外协单只能有一个供应商');
          return;
        }

        this.dialogTitle = '付款';
        this.selectWarehouse = this.warehouseList;
        this.dialogType = 'payment';
        this.openDialog = true;
      },

      paySuccess: function () {
        this.openDialog = false;
        this.setWarehouseList();
      },

      dialogClosed: function () {
        this.dialogTitle = '';
        this.dialogType = null;
        this.selectWarehouse = null;
      },

      balanceOrder: function (warehouse) {
        var self = this;
        this.$confirm('确定要结算此外协单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(function () {
          self.toBalanceOrder(warehouse);
        }).catch(function () {});
      },

      toBalanceOrder: function (warehouse) {
        this.loading = true;
        var self = this;
        ajaxRequest('warehouseInSumMoney/setIsBalanceByWarehouseInSumId', {
          id: warehouse.typeId,
          isBalance: '1',
          money: warehouse.totalPrice,
          isPutOut: 1,
          source: 1
        }).then(function (res) {
          self.$alert('结算成功', '信息', {
            callback: function () {
              self.setWarehouseList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      exportExcel: function () {
        this.search = _.cloneDeep(this.oldSearch);
        var postData = {};
        this.setPostData(postData);
        var formParam = SysUtil.formatFormParam(postData);
        var basePath = SysUtil.getBasePath();
        var path = `${basePath}/putOutNew/exportPutOutSumMoneyDetail?${formParam}`;
        window.open(path);
      },

      lookStat: function () {
        this.openStat = true;
      },

      statClosed: function (search) {
        if (!SysUtil.equalsObj(this.oldSearch, search)) {
          this.search = _.cloneDeep(search);
          this.oldSearch = _.cloneDeep(search);
          this.searchData();
        }
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      OutOrderSearchForm: OutOrderSearchForm,
      BalanceDetail: BalanceDetail,
      PaymentForm: PaymentForm,
      OutOrderBalanceStat: OutOrderBalanceStat
    },

    template: template
  };
}();
